package org.iridium.allcomments.servlets;

import java.io.IOException;
import java.math.BigDecimal;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.iridium.allcomments.buzz.UserBuzz;
import org.iridium.allcomments.dto.UserDTO;
import org.iridium.allcomments.exception.AllCommentsException;

/**
 * Servlet implementation class RegisterServlet
 */
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String loginName = request.getParameter("login_name");
		String password = request.getParameter("password");
		String email = request.getParameter("email");
		String nickname = request.getParameter("nickname");

		// TODO this operation can be taken on the page by js
		nickname = nickname.equals("") ? loginName : nickname;

		UserDTO user = new UserDTO();
		user.setUserId(this.generateUserId());
		user.setLoginName(loginName);
		user.setPassword(password);
		user.setEmail(email);
		user.setNickname(nickname);

		UserBuzz buzz = new UserBuzz();
		try {
			buzz.register(user);
		} catch (AllCommentsException e) {
			// TODO log
			e.printStackTrace();
		}

	}

	/**
	 * TODO if OOs Base can generate automatic number, this method will be
	 * disabled.
	 * 
	 * @return
	 */
	private long generateUserId() {
		return new BigDecimal(Math.random() * 1000000000).longValue();
	}

}
